#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/fcntl.h>

struct flock lock;

void set_lock(int fd, int cmd) {
    lock.l_type = F_WRLCK; // 设置为写锁
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0; // 锁定整个文件
    if (fcntl(fd, cmd, &lock) == -1) {
        perror("fcntl lock failed");
        exit(1);
    }
}

int main() {
    int fd = open("test.txt", O_RDWR | O_CREAT, 0666);
    if (fd == -1) {
        perror("open failed");
        exit(1);
    }
    set_lock(fd, F_SETLK);
    printf("Lock acquired, sleeping for 10 seconds...\n");
    sleep(10);
    close(fd);
    return 0;
}
